import cv2
import numpy as np
from matplotlib import pyplot as plt

# img = cv2.imread('d:\\test\\test4.jpg', 0)
# lower_reso = cv2.pyrDown(img)
# higher_reso2 = cv2.pyrUp(lower_reso)
#
# while(1):
#     cv2.imshow('image', img)
#     cv2.imshow('lower_reso', lower_reso)
#     cv2.imshow('higher_reso2', higher_reso2)
#     if cv2.waitKey() == ord('q'):
#         break
#
# cv2.destroyAllWindows()

A = np.asarray(cv2.imread('d:\\test\\apple.jpg'))

B = np.asarray(cv2.imread('d:\\test\\a.jpg'))

G = A.copy()
gpA = [G]
for i in range(6): #生成6层苹果图像高斯金字塔
    G =cv2.pyrDown(G)
    gpA.append(G)

G2 = B.copy()
gpB = [G2]
for i in range(6): #生成6层苹果图像高斯金字塔
    G2 =cv2.pyrDown(G2)
    gpB.append(G2)

lpA = [gpA[5]]#lpA赋值苹果高斯金字塔尖端，也就是最小段
for i in range(5,0,-1):#从苹果金字塔最尖端往上遍历
    GE = cv2.pyrUp(gpA[i])#在高斯金字塔图层生成拉普拉斯金字塔图层
    L = cv2.subtract(gpA[i - 1], GE) #此处需要注意，开始我使用的图片分辨率为320*240 连续除6次2，如果不能整除，代码会报错，此处是矩阵相加需要矩阵行列长度都相等
    lpA.append(L)#添加进拉普拉斯金字塔

lpB = [gpB[5]]
for i in range(5,0,-1):
    GE = cv2.pyrUp(gpB[i])
    L = cv2.subtract(gpB[i - 1], GE)
    lpB.append(L)

LS = []
for la,lb in zip(lpA,lpB):#利用zip把所有拉普拉斯金字塔变成list
    rows,cols,dpt = la.shape
    ls = np.hstack((la[:,0:cols//2], lb[:,cols//2:]))#苹果和橘子各半边按列对接
    LS.append(ls)

ls_ = LS[0]#赋值金字塔最小端
for i in range(1,6):#从小到大将对接好的图恢复成大图
    ls_ = cv2.pyrUp(ls_)
    ls_ = cv2.add(ls_, LS[i])

# image with direct connecting each half
real = np.hstack((A[:,:320],B[:,320:]))#原图各半对接用来对比
cv2.imwrite('D:\\test\\Pyramid_blending2.jpg',ls_)
cv2.imwrite('D:\\test\\Direct_blending.jpg',real)